package com.interview.thread.philosproblem;

import com.interview.thread.SleepHelper;

public class UnDeadLockTest {
    public static void main(String[] args) {

        Chopsticks c0 = new Chopsticks();
        Chopsticks c1 = new Chopsticks();
        Chopsticks c2 = new Chopsticks();
        Chopsticks c3 = new Chopsticks();
        Chopsticks c4 = new Chopsticks();

        Philosophers philosopher0 = new Philosophers("0",0,c0,c1);
        Philosophers philosopher1 = new Philosophers("1",1,c1,c2);
        Philosophers philosopher2 = new Philosophers("2",2,c2,c3);
        Philosophers philosopher3 = new Philosophers("3",3,c3,c4);
        Philosophers philosopher4 = new Philosophers("4",4,c4,c0);
        philosopher0.start();
        philosopher1.start();
        philosopher2.start();
        philosopher3.start();
        philosopher4.start();


    }

}

class Philosophers extends Thread {
    //哲学家名称
    private String name;
    //哲学家位置
    private Integer index;

    Chopsticks left ,right;

    Philosophers(String name,Integer index,Chopsticks left,Chopsticks right){
        this.name =name;
        this.index = index;
        this.left = left;
        this.right = right;
    }




    @Override
    public void run() {
        Long s = System.currentTimeMillis();
        //性能更好的方案是 index%2 ==0
        if(index%2 == 0){
            synchronized (left){
                SleepHelper.sleepSeconds(1);
                synchronized (right){
                    SleepHelper.sleepSeconds(1);
//                    System.out.println(name+"吃完了！");
                }
            }
        }else {
            synchronized (right){
                SleepHelper.sleepSeconds(1);
                synchronized (left){
                    SleepHelper.sleepSeconds(1);
//                    System.out.println(name+"吃完了！");
                }
            }
        }
        long s2 = System.currentTimeMillis();
        System.out.println(name+"吃完了!时间:"+(s2-s));

    }


}


